package com.xjscrm.console.biz;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.xjscrm.common.enums.TencentCosRegionEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.console.entity.TencentCosConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class TencentCosService {

    @Value("${tencent.cos.appId}")
    private String tencentCosAppId;

    @Value("${tencent.cos.secretId}")
    private String tencentCosSecretId;

    @Value("${tencent.cos.secretKey}")
    private String tencentCosSecretKey;

    @Value("${tencent.cos.region}")
    private String tencentCosRegion;

    @Value("${tencent.cos.bucketName}")
    private String tencentCosBucketName;

    private static Logger logger= LoggerFactory.getLogger(TencentCosService.class);

    public String uploadFile(MultipartFile file) {
        if(file == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择文件");
        }
        String fileUrl = "";
        String filename = file.getOriginalFilename();
        filename = UUID.randomUUID().toString().replace("-","") + filename.substring(filename.lastIndexOf("."));
        try {
            fileUrl = upload(file.getInputStream(), filename);
        }catch (Exception e){
            logger.error("--is error; error={}", e.getMessage());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "上传失败");
        }
        return fileUrl;
    }


    public COSClient createCOSClient(TencentCosConfig tencentCosConfig){
        //1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(tencentCosConfig.getSecretId(), tencentCosConfig.getSecretKey());
        // 2 设置 bucket 的地域
        Region region = new Region(tencentCosConfig.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);

        // 以下的设置，是可选的：

        // 设置 socket 读取超时，默认 30s
        //clientConfig.setSocketTimeout(30*1000);
        // 设置建立连接超时，默认 30s
        //clientConfig.setConnectionTimeout(30*1000);

        // 如果需要的话，设置 http 代理，ip 以及 port
        //clientConfig.setHttpProxyIp("httpProxyIp");
        //clientConfig.setHttpProxyPort(80);

        // 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }





    public String upload(InputStream inputStream, String fileName){
        String fileUrl = "";
        TencentCosConfig tencentCosConfig = new TencentCosConfig();
        tencentCosConfig.setAppId(tencentCosAppId);
        tencentCosConfig.setSecretId(tencentCosSecretId);
        tencentCosConfig.setSecretKey(tencentCosSecretKey);
        tencentCosConfig.setRegion(tencentCosRegion);
        tencentCosConfig.setBucketName(tencentCosBucketName);
        COSClient cosClient=null;
        try {
            cosClient= createCOSClient(tencentCosConfig);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 上传的流如果能够获取准确的流长度，则推荐一定填写 content-length
            // 如果确实没办法获取到，则下面这行可以省略，但同时高级接口也没办法使用分块上传了
            objectMetadata.setContentLength(inputStream.available());
            //objectMetadata.setContentType(contentType);
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentCosConfig.getBucketName(), fileName, inputStream, objectMetadata);

            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            if(putObjectResult != null ) {
                TencentCosRegionEnum tencentCosRegionEnum = TencentCosRegionEnum.getValue(tencentCosConfig.getRegion());
                if (tencentCosRegionEnum != null) {
                    fileUrl = "https://" + tencentCosRegionEnum.getDomain().replace("<BucketName>", tencentCosConfig.getBucketName()) + "/" + fileName;
                }
            }

        }catch (Exception e){
            logger.error("上传文件失败：error={}" +e.getMessage());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "上传失败");
        }finally {
            if(cosClient != null){
                cosClient.shutdown();
            }
        }
        return fileUrl;
    }
}
